<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>重置密码</span>
    </div>
    <el-form ref="form" label-width="110px" :model="pass" :rules="rules">
      <el-form-item label="原来密码" prop="old_pwd">
        <el-input v-model="pass.old_pwd"></el-input>
      </el-form-item>
      <el-form-item label="输入新密码" prop="new_pwd">
        <el-input v-model="pass.new_pwd"></el-input>
      </el-form-item>
      <el-form-item label="再次输入密码" prop="re_pwd">
        <el-input v-model="pass.re_pwd"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updatePwd">确认修改</el-button>
        <el-button>重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { updatePwdAPI } from '@/api/user'
export default {
  data() {
    // 自定义规则
    const newPwd = (rules, value, callback) => {
      if (value === this.pass.old_pwd) {
        callback(new Error('新密码不能原来密码相同'))
      } else {
        callback()
      }
    }
    const rePwd = (rules, value, callback) => {
      if (value === this.pass.new_pwd) {
        callback()
      } else {
        callback(new Error('两次密码不一致'))
      }
    }
    return {
      // 数据项/
      pass: {
        old_pwd: '',
        new_pwd: '',
        re_pwd: ''
      },
      // 验证规则对象
      rules: {
        old_pwd: [
          { required: true, message: '原密码必须填写', triggers: 'blur' },
          { min: 6, max: 15, message: '填写6到15数字', triggers: 'blur' }
        ],

        new_pwd: [
          { required: true, message: '新密码必须填写', triggers: 'blur' },
          { min: 6, max: 15, message: '填写6到15数字', triggers: 'blur' },
          { validator: newPwd, triggers: 'blur' }
        ],
        re_pwd: [
          { required: true, message: '再次填写密码', triggers: 'blur' },
          { min: 6, max: 15, message: '填写6到15数字', triggers: 'blur' },
          { validator: rePwd, triggers: 'blur' }
        ]
      }
    }
  },
  methods: {
    updatePwd() {
      this.$refs.form.validate(async valid => {
        if (!valid) return
        const { data: res } = await updatePwdAPI(this.pass)
        if (res.code === 0) {
          this.$message.success(res.message)
          this.$store.commit('user/updateToken', '')
          this.$store.commit('user/updateUser', {})
          this.$router.push('/login')
        } else {
          this.$messaage.Error(res.message)
        }
      })
    }
  }
}
</script>

<style lang="less" scoped></style>
